
package com.ruoyi.mall.app.service.impl;

import com.ruoyi.mall.app.mapper.DtsCartMapper;
import com.ruoyi.mall.common.domain.DtsUserCouponVo;
import com.ruoyi.mall.app.service.DtsCouponService;
import com.ruoyi.mall.common.domain.*;
import com.ruoyi.mall.common.mapper.DtsCouponMapper;
import com.ruoyi.mall.common.mapper.DtsGoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DtsCouponServiceImpl implements DtsCouponService {

    @Autowired
    private DtsCouponMapper couponMapper;
    @Autowired
    private DtsGoodsMapper goodsMapper;

    @Override
    public List<DtsUserCouponVo> getUserCouponList(Long userId, Integer status) {
        DtsCouponUser query = new DtsCouponUser();
        query.setUserId(userId);
        query.setStatus(status != null ? status.longValue() : null);
        List<DtsUserCouponVo> list = couponMapper.selectUserCouponList(query);

        return list;
    }

    @Override
    public int useCoupon(DtsCouponUser dtsCouponUser) {
        return couponMapper.updateCouponUserStatus(dtsCouponUser);
    }

    @Override
    public int getCouponCount(Long userId) {
        return couponMapper.getCouponCount(userId);
    }

    @Override
    public List<DtsCoupon> getAvailableCoupons(Long userId) {
        // 获取所有有效优惠券
        DtsCoupon query = new DtsCoupon();
        query.setStatus(0); // 0=正常可用
        List<DtsCoupon> allCoupons = couponMapper.selectDtsCouponList(query);

        // 过滤用户已领取且未使用的
        return allCoupons.stream()
                .filter(coupon -> !isUserHasCoupon(userId, coupon.getId()))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class) //添加事务注解
    public int receiveCoupon(Long userId, Long couponId) {
        // 1. 检查优惠券是否存在且可用
        DtsCoupon coupon = couponMapper.selectDtsCouponById(couponId);
        if (coupon == null || coupon.getStatus() != 0) {
            throw new RuntimeException("优惠券不可用");
        }

        // 2. 检查用户是否已领取
        if (isUserHasCoupon(userId, couponId)) {
            throw new RuntimeException("您已领取过此优惠券");
        }

        // 3. 检查领取数量限制
        DtsCouponUser query = new DtsCouponUser();
        query.setUserId(userId);
        query.setCouponId(couponId);
        int receivedCount = couponMapper.selectDtsCouponUserList(query).size();
        if (coupon.getLimit() != null && receivedCount >= coupon.getLimit()) {
            throw new RuntimeException("超过领取限制");
        }

        // 4. 创建用户优惠券记录
        DtsCouponUser userCoupon = new DtsCouponUser();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(couponId);
        userCoupon.setStatus(0L); // 未使用
        userCoupon.setAddTime(new Date());

        // 设置有效期
        if (coupon.getTimeType() == 0) { // 相对时间（基于领取时间）
            Calendar cal = Calendar.getInstance();
            userCoupon.setStartTime(cal.getTime());
            cal.add(Calendar.DATE, coupon.getDays());
            userCoupon.setEndTime(cal.getTime());
        } else { // 绝对时间（固定时间段）
            userCoupon.setStartTime(coupon.getStartTime());
            userCoupon.setEndTime(coupon.getEndTime());
        }
        // 更新优惠券库存
        DtsCoupon cons = new DtsCoupon();
        cons.setId(couponId);
        couponMapper.updateCouponTotal(cons);

        return couponMapper.insertDtsCouponUser(userCoupon);
    }

    @Override
    public int refundCoupon(DtsCouponUser dtsCouponUser) {
        return couponMapper.updateRefundCoupon(dtsCouponUser);
    }

    @Override
    public DtsCoupon getCouponById(Long id) {
        return couponMapper.selectDtsCouponById(id);
    }

    @Override
    public Long getCategoryIdByGoodsId(Long goodsId) {
        DtsGoods goods = goodsMapper.selectDtsGoodsById(goodsId);
        return goods != null ? goods.getCategoryId() : null;
    }


    private boolean isUserHasCoupon(Long userId, Long couponId) {
        DtsCouponUser query = new DtsCouponUser();
        query.setUserId(userId);
        query.setCouponId(couponId);
        query.setStatus(0L); // 未使用
        return couponMapper.selectDtsCouponUserList(query).size() > 0;
    }
}
